<template>
  <div>
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="0.48rem" class="goback" @click="$router.go(-1)" />
      <!-- 搜索组件 -->
      <van-search v-model.trim="kw" placeholder="请输入搜索关键词"
      background="#007BFF" shape="round" v-focus />
    </div>
    <div class="sugg-list">
    <div class="sugg-item" v-for="(item, i) in suggestList" :key="i" v-html='lightFn(item)'>
    </div>
</div>
 <div class="search-history">
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="(tag, i) in history" :key="i">{{
          tag
        }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { suggestListAPI } from '@/api'
export default {
  data () {
    return {
      kw: '', // 搜索关键字
      timer: '',
      suggestList: [], // 联想菜单数据
      history: ['API', 'java', 'css', '前端', '后台接口', 'python'] // 搜索历史
    }
  },
  watch: { // 监听关键词
    kw () {
      clearTimeout(this.timer) // 防抖：降低输入框触发频率清除上次计时器
      if (this.kw.length === 0) {
        this.suggestList = ''
        return
      }
      this.timer = setTimeout(async () => {
        console.log(this.kw);
        const [, res] = await suggestListAPI({ q: this.kw })
        // console.log(res);
        this.suggestList = res.data.data.options
      }, 900)
    }
  },
  methods: {
    lightFn (item) {
      const reg = new RegExp(this.kw, 'g') // 全局匹配
      return item.replace(reg, `<span style="color:red">${this.kw}</span>`)
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
